<template>
  <div>
    <Form
      oneitem="设备编号"
      :select-show="false"
      :search-list="vmSearchList"
      :config-click-show="true"
      :total-count="totalCount"
      :total-page="totalPage"
      :page-index="pageIndex"
      button-text="批量操作"
      @changeList="changeList"
      @newCreateFn="vmCreateFn"
      @handleSelectionChange="handleSelectionChange"
      @configCilck="configCilck"
      @searchResultFn="searchResultFn"
    >
      <template #tableForm>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="date" label="序号" width="80" type="index" :index="indexMethod" />
        <el-table-column prop="innerCode" label="设备编号" width="240" />
        <el-table-column prop="type.name" label="设备型号" />
        <el-table-column prop="node.addr" label="详细地址" />
        <el-table-column prop="ownerName" label="合作商" />
        <el-table-column prop="vmStatus" label="设备状态" />
        <el-table-column prop="address" label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="channelShowFn(scope.row)">货道</el-button>
            <el-button type="text" size="small" @click="policyEdit(scope.row)">策略</el-button>
            <el-button type="text" size="small" @click="edit(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </template>
    </Form>
    <!-- 新增 -->
    <el-dialog title="新增设备" :visible.sync="vmVisible" width="630px">
      <el-form ref="vmForm" :model="vmForm" :rules="vmRules">
        <el-form-item label="设备编号：">
          系统自动生成
        </el-form-item>
        <el-form-item label="选择型号：" prop="vmType">
          <el-select v-model="vmForm.vmType" placeholder="请选择">
            <el-option v-for="item in vmTypeOptions" :key="item.typeId" :label="item.name" :value="item.typeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择点位：" prop="nodeId">
          <el-select v-model="vmForm.nodeId" placeholder="请选择">
            <el-option v-for="item in nodeOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button id="buttom2" @click="vmVisible=false">取 消</el-button>
        <el-button id="buttom1" type="primary" @click="addVmFn">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog v-if="vmInfoVisible" title="新增设备" :visible.sync="vmInfoVisible" width="630px">
      <el-form ref="vmForm" :model="vmForm" :rules="vmRules">
        <el-form-item label="机器编号：">
          {{ editList.innerCode }}
        </el-form-item>
        <el-form-item label="供货时间：">
          {{ editList.lastSupplyTime }}
        </el-form-item>
        <el-form-item label="设备类型：">
          {{ editList.type.name }}
        </el-form-item>
        <el-form-item label="设备容量：">
          {{ editList.type.channelMaxCapacity }}
        </el-form-item>
        <el-form-item label="设备点位：">
          <el-select v-model="vmForm.nodeId" placeholder="请选择">
            <el-option v-for="item in nodeOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="合作商：">
          {{ editList.ownerName }}
        </el-form-item>
        <el-form-item label="所属区域：">
          {{ editList.region.name }}
        </el-form-item>
        <el-form-item label="设备地址：">
          {{ editList.node.addr }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button id="buttom2" @click="vmInfoVisible=false">取 消</el-button>
        <el-button id="buttom1" type="primary" @click="editVmFn">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 批量策略管理 -->
    <el-dialog title="批量策略管理" :visible.sync="policyVisible" width="630px" @open="policyOpen" @closed="policyClose">
      <el-form ref="policyForm" :model="policyForm">
        <el-form-item label="选择策略：">
          <el-select v-model="policyForm.policyId" placeholder="请选择">
            <el-option
              v-for="item in policyList"
              :key="item.policyId"
              :label="item.policyName"
              :value="item.policyId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button id="buttom2" @click="policyVisible=false">取 消</el-button>
        <el-button id="buttom1" type="primary" @click="policyYes">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 是否取消策略管理 -->
    <el-dialog v-if="policyInfo.innerCode" title="策略管理" :visible.sync="cancelPolicy" width="630px">
      <el-form :model="policyInfo">
        <el-row>
          <el-col :span="12">
            <el-form-item label="机器编号：">
              {{ policyInfo.innerCode }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="策略名称：">
              {{ policyInfo.policyName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="策略方案：">
              {{ policyInfo.discount }}%
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button id="buttom2" @click="cancelPolicyFn">取消策略</el-button>
      </div>
    </el-dialog>
    <!-- 货道弹窗 -->
    <el-dialog v-if="channelList.length" title="货道设置" :visible.sync="channelShow" width="940px">
      <!-- 添加商品 -->
      <el-dialog width="858px" title="选择商品" :visible.sync="addSkuVisible" append-to-body>
        <el-form>
          <el-form-item label="商品名称：" style="margin-right: 85px;">
            <el-input v-model="skuName" placeholder="" style="width: 400px;" />
            <el-button icon="el-icon-search" style="margin-left: 15px;background-color: #5f84ff;color: #fff;" @click="skuSearch">查询
            </el-button>
          </el-form-item>
        </el-form>
        <el-main style="width: 750px; margin:auto">
          <el-row>
            <el-col v-for="item in skuList" :key="item.skuId" :span="5">
              <div class="item space" @click="seleSkuFn(item)">
                <div class="sku">
                  <img
                    v-if="seleSkuInfo.skuId===item.skuId"
                    src=""
                    class="selected"
                  >
                  <img :src="item.skuImage">
                  <div class="name">
                    {{ item.skuName }}
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
          <svg-icon icon-class="right" class="icon-right" @click="skuListAdd" />
          <svg-icon icon-class="left" class="icon-left" @click="skuListSub" />
        </el-main>
        <div slot="footer" class="dialog-footer">
          <el-button id="buttom1" type="primary" :disabled="!seleSkuInfo.skuId" @click="addSkuFn">确认</el-button>
        </div>
      </el-dialog>
      <!--  -->
      <!-- 智能推荐 -->
      <el-dialog width="858px" title="智能排货" :visible.sync="businessTopVisible" append-to-body>
        <el-main style="width: 750px; margin:auto">
          <div style="margin-bottom:16px">该区域属于{{ businessName }}商圈适合销售一下商品：</div>
          <el-row>
            <el-col v-for="item in businessTopList" :key="item.skuId" :span="5">
              <div class="item space">
                <div class="sku">
                  <img :src="item.image">
                  <div class="name">
                    {{ item.skuName }}
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-main>
        <div slot="footer" class="dialog-footer">
          <el-button id="buttom1" type="primary" @click="addBusinessList">采纳建议</el-button>
        </div>
      </el-dialog>
      <el-container>
        <el-header>
          <div class="channel-header">
            <div>
              <span>货道行数：{{ vmTypeInfo.vmRow }}</span>
              <span>货道列数：{{ vmTypeInfo.vmCol }}</span>
              <span>货道容量（个）：{{ vmTypeInfo.channelMaxCapacity }}</span>
            </div>
            <el-button @click="businessTopFn">智能排货</el-button>
          </div>
        </el-header>
        <el-main>
          <el-scrollbar ref="scroll">
            <el-row v-for="(num,index) in vmTypeInfo.vmRow " :key="index" type="flex">
              <el-col
                v-for="item in channelList.slice(vmTypeInfo.vmCol*index,vmTypeInfo.vmCol*num)"
                :key="item.channelId"
                :span="12"
                style="padding-left: 8px; padding-right: 8px;"
              >
                <div class="item">
                  <div class="code">
                    {{ item.channelCode }}
                  </div>
                  <div class="sku">
                    <img
                      :src="item.sku?item.sku.skuImage:''"
                    >
                    <div class="name">
                      {{ item.sku?item.sku.brandName:'暂无商品' }}
                    </div>
                  </div>
                  <div>
                    <el-button type="text" @click="addSku(item.channelCode)">添加</el-button>
                    <el-button type="text" style="color:red" @click="delSku(item.channelCode)">删除</el-button>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-scrollbar>
          <svg-icon icon-class="right" class="icon-right" @click="rightScrol" />
          <svg-icon icon-class="left" class="icon-left" @click="leftScrol" />
        </el-main>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button id="buttom1" type="primary" @click="channelConfigFn">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Form from '@/components/form/index.vue'
import {
  vmSearchList, vmTypeSearch, nodeSearch, addVm, editVm,
  policyList, applyPolicy, vmPolicy, cancelPolicy, channelList,
  vmTypeApi, skuSearchList, channelConfig, businessTop
} from '@/api'
export default {
  components: { Form },
  data() {
    return {
      dom: null,
      vmSearchList: [],
      pageIndex: 1,
      totalPage: null,
      totalCount: null,
      vmVisible: false,
      vmInfoVisible: false,
      policyVisible: false,
      cancelPolicy: false,
      channelShow: false,
      addSkuVisible: false,
      businessTopVisible: false,
      vmForm: {
        vmType: null,
        nodeId: null
      },
      vmRules: {
        vmType: [{ required: true, message: '请输入' }],
        nodeId: [{ required: true, message: '请输入' }]
      },
      vmTypeOptions: [],
      nodeOptions: [],
      editList: {},
      // multipleSelection: [],
      // innerCodeList: [],
      policyList: [],
      policyForm: {
        innerCodeList: [],
        policyId: null
      },
      policyInfo: {
        innerCode: ''
      },
      businessId: null, // 智能排货参数
      businessName: null,
      channelList: [], // 货道列表
      vmTypeInfo: {},
      skuList: [], // 商品列表
      skuTotalPage: null, // 所有商品页数
      skuName: '', // 商品名称
      addPageIndex: 1,
      channelCode: null, // 选择的货道code
      seleSkuInfo: {}, // 添加的商品
      selseCode: null, // 选择修改商品的code
      businessTopList: []
    }
  },
  created() {
    this.vmList(this.pageIndex)
  },
  methods: {
    // 列表函数
    async vmList(pageIndex, innerCode) {
      const res = await vmSearchList({
        pageIndex,
        pageSize: 10,
        innerCode
      })
      this.vmSearchList = res.data.currentPageRecords
      this.vmSearchList.forEach(item => {
        item.node.addr = item.node.addr.split('-').at(-1)
        if (item.vmStatus === 0) {
          item.vmStatus = '未投放'
        } else if (item.vmStatus === 1) {
          item.vmStatus = '运营'
        } else {
          item.vmStatus = '撤机'
        }
      })
      this.totalPage = res.data.totalPage
      this.totalCount = res.data.totalCount
    },
    indexMethod(index) {
      return this.pageIndex === 1 ? index + 1 : Number(`${this.pageIndex - 1}${index}`) + 1
    },
    changeList(page) {
      this.pageIndex = page
      this.vmList(this.pageIndex)
    },
    // 搜索
    searchResultFn(val) {
      this.vmList(1, val.taskCode)
    },
    // 关闭弹窗
    vmClose() {
      // this.$refs.vmForm.resetFields()
    },
    // 新建
    async vmCreateFn() {
      const res = await vmTypeSearch({
        pageIndex: 1,
        pageSize: 100000
      })
      const res1 = await nodeSearch({
        pageIndex: 1,
        pageSize: 100000
      })
      this.vmTypeOptions = res.data.currentPageRecords
      this.nodeOptions = res1.data.currentPageRecords
      this.vmVisible = true
    },
    // 确定新建
    addVmFn() {
      this.$refs.vmForm.validate(async(valid) => {
        if (!valid) return
        const res = await addVm({
          ...this.vmForm,
          createUserId: this.$store.state.user.userId
        })
        if (res.data) {
          this.$message({
            type: 'success',
            message: '新增成功'
          })
          this.vmList(this.pageIndex)

          this.vmVisible = false
        }
      })
    },
    // 修改
    async edit(row) {
      const res1 = await nodeSearch({
        pageIndex: 1,
        pageSize: 100000
      })
      this.nodeOptions = res1.data.currentPageRecords
      this.vmInfoVisible = true
      this.editList = row
      this.vmForm.nodeId = row.node.id
    },
    // 确定修改
    async editVmFn() {
      await editVm(this.editList.id, this.vmForm.nodeId).then(() => {
        this.$message({
          type: 'success',
          message: '修改成功'
        })
        this.vmList(this.pageIndex)
        this.vmInfoVisible = false
      }).catch(res => {
        this.$message({
          type: 'error',
          message: res.response.data
        })
      })
    },
    handleSelectionChange(val, dom) {
      this.dom = dom
      this.policyForm.innerCodeList = []
      val.forEach(item => {
        this.policyForm.innerCodeList.push(item.innerCode)
      })
    },
    // 策略弹窗打开函数
    async policyOpen() {
      const res = await policyList()
      // console.log(res.data)
      this.policyList = res.data
    },
    // 关闭时
    policyClose() {
      this.policyForm.innerCodeList = []
      if (this.dom) {
        this.dom.clearSelection()
      }
    },
    // 策略管理按钮
    configCilck() {
      if (this.policyForm.innerCodeList.length) {
        this.policyVisible = true
      } else {
        this.$message({
          type: 'warning',
          message: '请勾选售货机'
        })
      }
    },
    // 确定应用
    async policyYes() {
      await applyPolicy(this.policyForm).then(() => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.dom.clearSelection()
      }).catch(res => {
        this.$message({
          type: 'error',
          message: res.response.data
        })
      })
      this.policyVisible = false
    },
    // 策略按钮
    async policyEdit(row) {
      await vmPolicy(row.innerCode).then(res => {
        if (!res.data) {
          this.policyForm.innerCodeList.push(row.innerCode)
          this.policyVisible = true
        } else {
          this.policyInfo = res.data
          this.cancelPolicy = true
        }
      })
    },
    // 取消策略
    async cancelPolicyFn() {
      await cancelPolicy(this.policyInfo.innerCode, this.policyInfo.policyId).then(() => {
        this.$message({
          type: 'success',
          message: '取消策略成功'
        })
      }).catch(res => {
        this.$message({
          type: 'warning',
          message: res.response.data
        })
      })
      this.cancelPolicy = false
    },
    // 货物
    async channelShowFn(row) {
      // console.log(row.node.businessType.name)
      this.businessName = row.node.businessType.name
      this.businessId = row.businessId
      this.channelCode = row.innerCode
      const res = await channelList(row.innerCode)
      const res1 = await vmTypeApi(row.type.typeId)
      this.vmTypeInfo = res1.data
      this.channelList = res.data
      this.channelShow = true
    },
    // 补货推荐列表
    async businessTopFn() {
      const res = await businessTop(this.businessId)
      // console.log(res.data)
      this.businessTopList = res.data
      this.businessTopVisible = true
    },
    // 采纳建议
    addBusinessList() {
      // console.log(this.businessTopList)
      this.businessTopList.forEach((item, index) => {
        item.skuImage = item.image
        this.channelList[index].sku = item
      })
      // console.log(this.channelList)
      this.businessTopVisible = false
    },
    // 向右滚动
    rightScrol() {
      this.$refs['scroll'].wrap.scrollTo({
        left: 847,
        behavior: 'smooth'
      })
    },
    leftScrol() {
      this.$refs['scroll'].wrap.scrollTo({
        left: -1000,
        behavior: 'smooth'
      })
    },
    // 商品接口
    async skuSearchListApi(pageIndex, skuName) {
      const res = await skuSearchList({
        pageIndex,
        pageSize: 10,
        skuName
      })
      return res.data
    },
    // 添加商品
    async addSku(val) {
      this.skuList = []
      this.selseCode = val
      console.log(val)
      const res = await this.skuSearchListApi(this.addPageIndex)
      console.log(res)
      this.skuList = res.currentPageRecords
      this.skuTotalPage = res.totalPage
      this.addSkuVisible = true
    },
    // 搜索商品
    async skuSearch() {
      const res = await this.skuSearchListApi(this.addPageIndex, this.skuName)
      console.log(res)
      this.skuList = res.currentPageRecords
      this.skuTotalPage = res.totalPage
      this.skuName = ''
      this.addPageIndex = 1
    },
    // 下一页商品
    async skuListAdd() {
      if (this.addPageIndex >= this.skuTotalPage) {
        return
      }
      this.addPageIndex++
      const res = await this.skuSearchListApi(this.addPageIndex)
      this.skuList = res.currentPageRecords
    },
    // 上一页商品
    async skuListSub() {
      if (this.addPageIndex <= 1) {
        return
      }
      this.addPageIndex--
      const res = await this.skuSearchListApi(this.addPageIndex)
      this.skuList = res.currentPageRecords
    },
    seleSkuFn(item) {
      this.seleSkuInfo = item
      console.log(item)
    },
    // 确定添加(货道配置)
    addSkuFn() {
      this.channelList.forEach((item, index) => {
        if (item.channelCode === this.selseCode) {
          this.channelList[index].sku = this.seleSkuInfo
        }
      })
      this.addSkuVisible = false
      this.seleSkuInfo = {}
    },
    // 删除商品按钮
    delSku(row) {
      console.log(row)
      this.channelList.forEach((item, index) => {
        if (item.channelCode === row) {
          this.channelList[index].sku = null
        }
      })
      console.log(this.channelList)
    },
    // 货道配置处理函数
    channelListFn() {
      const arr = []
      this.channelList.forEach((item) => {
        // console.log(item.sku.skuId)
        const obj = {}
        if (item.sku) {
          obj.skuId = item.sku.skuId
        } else {
          obj.skuId = 0
        }
        obj.channelCode = item.channelCode
        arr.push(obj)
      })
      console.log(arr)
      return arr
    },
    // 确定设置货道
    async channelConfigFn() {
      await channelConfig({
        channelList: this.channelListFn(),
        innerCode: this.channelCode
      }).then(() => {
        this.$message({
          type: 'success',
          message: '货道设置成功'
        })
      }).catch(res => {
        this.$message({
          type: 'warning',
          message: res.response.data
        })
      })
      this.channelShow = false
    }
  }

}
</script>

<style lang="scss" scoped>
.channel-header {
  align-items: center;
  width: 847px;
  height: 56px;
  border-radius: 5px;
  color: #666;
  line-height: 56px;
  font-size: 14px;
  margin: 0 auto;
  margin-bottom: 16px;
  background: #f3f6fb;
  display: flex;
  justify-content: space-between;

  span {
    margin-left: 43px;
  }

  .el-button {
    margin-right: 22px;
    background-color: #5f84ff;
    min-width: 80px;
    height: 36px;
    color: #fff;
  }
}

.el-scrollbar {
  width: 820px;
  height: 384px;
  margin: 0 auto;

  // background-color: #5f84ff;
  .el-col {
    width: 50%;

  }
}

.item {
  width: 150px;
  // height: 180px;
  text-align: center;
  box-shadow: 0 2px 4px 0 rgb(0 0 0 / 6%);
  border-radius: 4px;
  position: relative;

  .sku {
    height: 135px;
    padding-top: 16px;
    background-color: #f6f7fb;
    border-radius: 4px;

    img {
      display: inline-block;
      width: 84px;
      height: 78px;
      margin-bottom: 10px;
    }
  }

  .code {
    position: absolute;
    top: 10px;
    left: 0;
    width: 43px;
    height: 23px;
    line-height: 23px;
    background: #829bed;
    border-radius: 0 10px 10px 0;
    font-size: 12px;
    color: #fff;
  }
}

.icon-right {
  position: absolute;
  top: 50%;
  right: 10px;
  width: 50px !important;
  height: 50px !important;
  cursor: pointer;
}

.icon-left {
  position: absolute;
  top: 50%;
  left: 15px;
  width: 50px !important;
  height: 50px !important;
  cursor: pointer;
}

.space {
  margin-bottom: 20px;
  width: 134px;
  height: 134px;
  cursor: pointer;
}

.el-col-5 {
  width: 19% !important;
}

.selected {
  position: absolute;
  top: 0;
  left: 0;
  width: 36px !important;
  height: 36px !important;
}
</style>
